#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<stack>

using namespace std;

class Solution {
public:
    void replace(string& s) {
        int pos = s.find(" ");
        while (pos != -1) {
            s.replace(pos, 1, "");
            pos = s.find(" ");
        }
    }
    int calculate(string s) {
        stack<int> nums;
        stack<char> ops;
        replace(s);
        int n = s.size();
        nums.push(0);
        for (int i = 0; i < s.size(); i++)
        {
            int c = s[i];
            if (c == '(')      ops.push(c);
            else if (c == ')')
            {
                while (ops.size())
                {
                    char op = ops.top();
                    if (op != '(')
                        calc(nums, ops);
                    else
                    {
                        ops.pop();
                        break;
                    }
                }
            }
            else if (c <= '9' && c >= '0')
            {
                int t = 0;
                int j = i;
                while (j < n && isdigit(s[j]))
                    t = t * 10 + (s[j++] - '0');
                nums.push(t);
                i = j - 1;
            }
            else if (c != ' ')
            {
                if (i > 0 && (s[i - 1] == '(' || s[i - 1] == '+' || s[i - 1] == '-'))
                    nums.push(0);
                while (ops.size() && ops.top() != '(')
                    calc(nums, ops);
                ops.push(c);
            }
        }
        while (ops.size())
            calc(nums, ops);
        return nums.top();
    }

    void calc(stack<int>& nums, stack<char>& ops)
    {
        if (nums.size() < 2 || ops.empty())
            return;
        int sec = nums.top();
        nums.pop();
        int fir = nums.top();
        nums.pop();
        char op = ops.top();
        ops.pop();
        nums.push(op == '+' ? fir + sec : fir - sec);
    }
};